package vmi.surgis;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.graphics.PointF;

public class DBmanager {
	private String dbHostUri;
	private HttpClient client;
	private HttpGet request;
	
	private boolean isConnected() {
		try {
    		this.request.setURI(new URI(this.dbHostUri));
    		HttpResponse response = client.execute(request);
    		int status = response.getStatusLine().getStatusCode();
    		if (status == 200) {
    			return true;
    		}
    		else {
    			return false;
    		}   		
    	}
    	catch (Exception e){
    		return false;
    	}
	}
	
	public DBmanager(String dbHostUri) {
		this.dbHostUri = dbHostUri;
		this.client = new DefaultHttpClient();
		this.request = new HttpGet();
	}
	
	private String getUriForPlace(String placeName) {
		String result = this.dbHostUri + "?place=" + placeName;
		return result;
	}
	
	private PointF getCoordFromString(String coordStr) {
		String[] coord = coordStr.split(";");
		Float x = Float.parseFloat(coord[0]),
			  y = Float.parseFloat(coord[1]);
		return new PointF(x, y);				
	}
	
	public PointF getCoord(String place) throws IOException, URISyntaxException {
		BufferedReader in = null;
		try {
			request.setURI(new URI(getUriForPlace(place)));
    		HttpResponse response = client.execute(request);
    		in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    		StringBuffer sb = new StringBuffer("");
    		String line = "";
    		String NL = System.getProperty("line.separator");
    		while ((line = in.readLine()) != null) {
    			sb.append(line + NL);
    		}
    		in.close();

    		try{
    	        JSONArray jArray = new JSONArray(sb.toString());
    	        JSONObject json_data = jArray.getJSONObject(0);
    	        String coordStr = json_data.getString("coord");
    	        return getCoordFromString(coordStr);
    		}
    		catch(JSONException e){
    	        return null;
    		}  		
    	}
    	finally {
    		if (in != null) {
    			try {
    				in.close();
    			}
    			catch (IOException e) {
    				e.printStackTrace();
    			}
    		}
    	}
	}
}
